package com.joro.ejb;

import java.util.Collection;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.app.LoggingUtil;
import com.joro.Magazine;
import com.joro.Supplier;
import com.joro.Supplier;

/**
 * Session Bean implementation class SupplierFacade
 */
@Stateless
public class SupplierFacade implements SupplierFacadeLocal {

	@PersistenceContext(unitName = "magazine.ejb")
	EntityManager manager;

	/**
	 * Default constructor.
	 */
	public SupplierFacade() {
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public void saveSupplier(Supplier pSupplier){
		LoggingUtil.logOperation(LoggingUtil.OPERATION_UPDATE, pSupplier);
		manager.merge(pSupplier);
	}
	
	@Override
	public Collection<Supplier> getSuppliers(){
		Query query = manager.createQuery("SELECT e FROM Supplier e");
		List<Supplier> resultList = query.getResultList();
		return resultList;
	}
	
	public Supplier getSupplierById(int pSupplierId){
		Query query = manager.createQuery("SELECT e FROM Supplier e WHERE e.id = :id");
		query.setParameter("id", pSupplierId);
		List<Supplier> resultList = query.getResultList();
		if(resultList.size() == 0)
			return null;
		return resultList.get(0);
	}

	@Override
	public void deleteSupplier(Supplier pSupplier) {
		LoggingUtil.logOperation(LoggingUtil.OPERATION_DELETE, pSupplier);
		manager.remove(manager.contains(pSupplier) ? pSupplier : manager.merge(pSupplier));		
	}

	@Override
	public Collection<Supplier> getSuppliersByMagazineId(int magazineID) {
		Query query = manager.createQuery("SELECT e FROM Magazine e WHERE e.id = :id");
		query.setParameter("id", magazineID);
		List<Magazine> resultList = query.getResultList();
		if(resultList.size() == 0)
			return null;
		Magazine magazine = resultList.get(0);
		query = manager.createQuery("SELECT e FROM Supplier e WHERE :magazine MEMBER OF e.magazines");
		query.setParameter("magazine", magazine);
		return query.getResultList();
	}

}
